package cn.wolfcode.servlet;

import cn.wolfcode.domain.File;
import cn.wolfcode.mapper.FileMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.ProductQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IFileService;
import cn.wolfcode.service.Impl.FileServiceImpl;
import cn.wolfcode.utils.MybatisUtil;
import cn.wolfcode.utils.StringUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@WebServlet("/chaxunServlet")
@MultipartConfig(maxFileSize = 800000, maxRequestSize = 1400000)
public class chaxunServlet extends HttpServlet {
    SqlSession session = null;
    FileMapper fileMapper=null;
    IFileService fileService = new FileServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String cmd = req.getParameter("cmd");
        if("delete".equals(cmd)){
            delete(req, resp);
        }else if("zhuxiao".equals(cmd)){
            zhuxiao(req, resp);
        }else if("xiazai".equals(cmd)){
            xiazai(req,resp);
        }else if("input".equals(cmd)){
            input(req, resp);
        }else if("saveOrUpdate".equals(cmd)){
            saveOrUpdate(req, resp);
        }else if("input2".equals(cmd)){
            input2(req, resp);
        }/*else if("saveOrUpdate2".equals(cmd)){
            saveOrUpdate2(req, resp);
        }*/else {
            list(req,resp);
        }
    }
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //QueryObject qo = new QueryObject();
        session=MybatisUtil.openSession();
       fileMapper = session.getMapper(FileMapper.class);
        Long uid = (Long)req.getSession().getAttribute("uid");
        ProductQueryObject qo = new ProductQueryObject();
        //String uid=req.getParameter("uid");
        if (StringUtils.hasLength(uid)){
            qo.setUid(uid);
        }
        String currenPage = req.getParameter("currenPage");
        if (StringUtils.hasLength(currenPage)) {
            qo.setCurrentPage(Integer.valueOf(currenPage));
        }
        String pageSize = req.getParameter("pageSize");
        if (StringUtils.hasLength(pageSize)) {
            qo.setPageSize(Integer.valueOf(pageSize));
        }
        PageResult<File> pageResult = fileService.query(qo);
        for (File datum : pageResult.getData()) {
            System.out.println(datum);
        }
        req.setAttribute("pageResult", pageResult);
        req.setAttribute("qo",qo);
        req.getRequestDispatcher("/WEB-INF/chaxun.jsp").forward(req, resp);
        session.close();
    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        session=MybatisUtil.openSession();
        fileMapper = session.getMapper(FileMapper.class);
        String strId = req.getParameter("id");
        System.out.println(strId);
        fileMapper.delete(Long.parseLong(strId));
        session.commit();
        session.close();
        resp.sendRedirect("/chaxunServlet");
    }
    protected void zhuxiao(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect("index.jsp");
    }
    protected void xiazai(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filepath=req.getParameter("filepath");
        String filename=req.getParameter("filename");
        String header = req.getHeader("User-Agent");
        String name = header.contains("MSIE") ? URLEncoder.encode(filename, "UTF-8") : new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        resp.setHeader("Content-Disposition", "attachment;filename=" + name);
        String realPath = req.getServletContext().getRealPath("/");
        Files.copy(Paths.get(realPath, filepath), resp.getOutputStream());
    }
    protected void input(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        session=MybatisUtil.openSession();
        fileMapper = session.getMapper(FileMapper.class);
        String id = req.getParameter("id");
        if (!id.equals(null)) {
            int i = Integer.parseInt(id);
            File f=fileMapper.selectid(i);
            req.setAttribute("f", f);
            req.getRequestDispatcher("/WEB-INF/xiugai.jsp").forward(req, resp);
            return;
        }
        System.out.println("f");
    }
    protected void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        session=MybatisUtil.openSession();
        fileMapper = session.getMapper(FileMapper.class);
        long id = Long.parseLong(req.getParameter("id"));
        String filename=req.getParameter("filename");
        Part part = req.getPart("filepath");
        String realFileName = part.getSubmittedFileName();
        String ext = realFileName.substring(realFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + ext;
        String realPath = getServletContext().getRealPath("/upload") + "/" + fileName;
        String via = "/upload/" + fileName;
        System.out.println(via);
        part.write(realPath);
        File f=new File(id,filename,via);
        System.out.println(f);
        fileMapper.update(f);
        session.commit();
        session.close();
        resp.sendRedirect("/chaxunServlet");
    }
    protected void input2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/tianjia.jsp");
    }
    /*protected void saveOrUpdate2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("filepath");
        //String realFileName = part.getSubmittedFileName();
        String cd = part.getHeader("Content-Disposition");
        //截取不同类型的文件需要自行判断
        String filename = cd.substring(cd.lastIndexOf("=")+2, cd.length()-1);
        String realFileName= filename ;
        System.out.println(filename);
        String ext = realFileName.substring(realFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + ext;
        String realPath = getServletContext().getRealPath("/upload") + "/" + fileName;
        String via = "/upload/" + fileName;
        System.out.println(via);
        part.write(realPath);
        Long uid = Long.parseLong(req.getParameter("uid")) ;
        File f = new File(filename,via,uid);
        System.out.println(f);
        fileMapper.insert(f);
        session.commit();
        session.close();
        resp.sendRedirect("/chaxunServlet");
    }*/
}
